package com.example.tianyidemo.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.example.tianyidemo.pojo.Result;
import com.example.tianyidemo.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Enumeration;

//拦截器(拦截无token信息请求)
@Slf4j

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override//目标资源方法运行前运行，返回ture放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //获取请求的url
        log.info(request.getRequestURI());
        String url = request.getRequestURI().toString();
        log.info("请求的url：{}",url);
        //判断请求的url中是否包含login，如果包含，说明是登录操作，放行
        if (url.contains("login")){
            log.info("登录操作，放行");
            return true;
        }
        if (url.contains("mail")){
            log.info("登录操作，放行");
            return true;
        }
        // 输出所有请求头信息
        Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headerName = headers.nextElement();
            String headerValue = request.getHeader(headerName);
            log.info("Request Header: {}: {}", headerName, headerValue);
        }

        //获取请求头的的令牌token
        String jwt = request.getHeader("token");
        log.info(jwt);
        //判断令牌是否存在，不存在返回错误就结果
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头中的token信息为空，返回未登录的信息");
            Result error = Result.error("NOT INdex");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        //解析token失败，返回错误结果
        try{
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析失败，返回错误信息");
            Result error = Result.error("NOT INdexToken");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
//        放行
        log.info("令牌配对成功，放行！");
        return true;
    }
    @Override//目标资源运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }
    @Override//视图渲染后完成，最后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion(完成后完成)...");
    }
}
